/**
 * Created by Bensn on 16/5/31.
 */

'use strict';

var errTitle = '异常';
var warTitle = '错误';
var errMsg = '服务器异常，请联系管理员';
var imgTitle = '预览图片';

$(function () {
    formAjax($('form'));
    tableSort($('.table-sort'));
    tabCookies();
    coverClick();
    selectDefault();

    skinInput();
    checkAll($(".table"));
});
//选择科室
function onchangeDepartment(jqObj){
    var department_id = jqObj.val();
    var diseaseSelect = $('select[name="disease_id"]');
    diseaseSelect.html('');
    $.ajax({
        url: '{:U("Disease/getListJson")}?department_id=' + department_id,
        type: 'post',
        enctype: 'multipart/form-data',
        success: function (data) {
            $.each(data, function (i, item) {
                diseaseSelect.append('<option value="' + item.id + '" >' + item.title + '</option>');
            });
        }
    });
}

//全局搜索
function searchAll(type){
    var key = $("input[name='keyword']").val();
    // var select =   $("#select").val();
    if(key){
        var url = "?keywords="+key+"&type="+type;
        goUrl(url);
    }else {
        // alert('请输入关键字');
        layer.msg('请输入关键字')
    }
}
//selct，checkbox的hui样式
function skinInput(){
    $('.skin-minimal input').iCheck({
        checkboxClass: 'icheckbox-blue',
        radioClass: 'iradio-blue',
        increaseArea: '20%'
    });
}

function selectDefault() {

}

/**
 * 记住页面tab位置
 */
function tabCookies() {
    var tabBar = $('.tabBar span');
    tabBar.bind('click', function () {
        var index = $(this).index();
        var tabId = 'tab_' + window.location.href;
        $.cookie(tabId, index);
    })
}

/**
 * 获取tab位置
 */
function getTabIndex() {
    var tabId = 'tab_' + window.location.href;
    return $.cookie(tabId) ? $.cookie(tabId) : 0;
}

/**
 * table排序
 * @param obj
 */
function tableSort(obj) {
    var actionColumnIndex = $('thead th').length;
    if (!actionColumnIndex || actionColumnIndex < 1) {
        return;
    }
    obj.dataTable({
        "aaSorting": [[1, "desc"]],
        "bStateSave": false,
        "aoColumnDefs": [
            {
                "orderable": false, "aTargets": [0, actionColumnIndex - 1]
            }
        ],
        "aLengthMenu": [[20], [20]],
        "sPaginationType": "full_numbers"
    });

//    $('.table-sort').dataTable({
//        "aaSorting": [[ 1, "asc" ]],//默认第几个排序
//        "bStateSave": false,//状态保存
//        "aoColumnDefs": [
//            {"orderable":false,"aTargets":[0]}// 制定列不参与排序
//        ],
//        "aLengthMenu": [[10,20], [10,20]],
//        "sPaginationType": "full_numbers",
//        "sDom": '<"top"fli>rt<"bottom">p<"clear">',
//    });
}

/**
 * 全选反选
 * @param obj
 * 1反选
 * 2全选
 */
function checkAll(obj, type) {
    var checkboxs = obj.find('input[type="checkbox"]');
    if (type == 1) {
        checkboxs.each(function (i) {
            alert(i);
            var item = checkboxs.eq(i);
            var isChek = item.is(':checked');
            item.prop('checked', !isChek);
        });
    }
    if (type == 2) {
        checkboxs.prop('checked', true);
    }
}

/**
 * 打开一个新的tab
 * @param obj
 */
function showTab(obj) {
    Hui_admin_tab(obj);
}

/*弹出添加*/
function showAdd(title, url, w, h) {
    layer_show(title, url, w, h);
}
/*弹出编辑*/
function showEdit(title, url, id, w, h) {
    alert(312);
    layer_show(title, url + '?id=' + id, w, h);
}

/**
 * 弹出覆层
 * @param title
 * @param url
 * @param w
 * @param h
 */
function showIframe(title, url, w, h) {
    w = w ? w + "px" : '';
    h = h ? h + "px" : '';
    var index = layer.open({
        type: 2,
        title: title,
        content: url,
        area: [w, h],
        scrollbar: false
    });
    if ((!w || w == '') && (!h || h == '')) {
        layer.full(index);
    }
}

/**
 * 删除提示
 * @param url
 */
function delectOne(url) {
    layer.confirm('确认要删除吗？', function () {
        requestUrl(url);
    });
}
/**
 * 恢复删除提示
 * @param url
 */
function recover(url) {
    layer.confirm('确认要恢复删除吗？', function () {
        requestUrl(url);
    });
}

//显示已删除内容
function showdeleted(isdel){
    if(isdel){
        //alert(0);
        goUrl('?del=1');
    }else{
        goUrl('?del=0');
    }
}

/**
 * 删除选中
 * @param url
 * @param itemObj
 */
function delectCheck(url, itemObj) {
    var size = $('.item:checked').size();
    if (size == 0){
        layer.msg('请选择要操作的项');
    }else{
        layer.confirm('确认要删除选中数据吗？', function (index) {
            layer.close(index);
            var itemAll = itemObj;
            var ids = '';
            for (var i = 0; i < itemAll.size(); i++) {
                var item = itemAll.eq(i);
                var id = item.val();
                if (id > 0) {
                    if (!item.is(':checked')) {
                        continue;
                    }
                    ids += id + ',';
                }
            }
            requestUrl(url + '?id=' + ids);
        });
    }
}

/**
 * 审核、驳回选中
 * @param url
 * @param itemObj
 * @param review
 */
function reviewedCheck(url, itemObj, review) {
    var size = $('.item:checked').size();
    if (size == 0){
        layer.msg('请选择要操作的项');
    }else {
        var msg = '';
        if (review == 1){
            msg = '审核';
        }else {
            msg = '驳回';
        }
        layer.confirm('确认要'+msg+'选中数据吗？', function (index) {
            layer.close(index);
            var itemAll = itemObj;
            var ids = '';
            for (var i = 0; i < itemAll.size(); i++) {
                var item = itemAll.eq(i);
                var id = item.val();
                if (id > 0) {
                    if (!item.is(':checked')) {
                        continue;
                    }
                    ids += id + ',';
                }
            }
            requestUrl(url + '?id=' + ids);
        });
    }
}

/**
 * ajax提交表单
 * @param formObj
 */
function formAjax(formObj) {
    var count = formObj.length;
    for (var i = 0; i < count; i++) {
        var formItem = formObj.eq(i);
        formItem.Validform({
            tiptype: function (msg, o, cssctl) {
                if (o.type == 3) {
                    layer.msg(msg, function(){});
                }
            },
            callback: function (form) {
                var layars = layer.load(0, {shade: [0.8, '#fff']});
                formItem.ajaxSubmit({
                    url: formItem.attr('action'),
                    type: 'post',
                    enctype: 'multipart/form-data',
                    success: function (data) {
                        layer.close(layars);
                        runAjaxResSuccess(data);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        layer.close(layars);
                        runAjaxResError(XMLHttpRequest, textStatus, errorThrown);
                    }
                });
                return false;
            }
        });
    }
}

/**
 * 跳转url
 * @param url
 * @param obj
 */
function goUrl(url, obj) {
    obj = obj ? obj : self;
    obj.location = url;
}


/**
 * ajax提交
 * */
function requestUrl(url) {
    var layars = layer.load(0, {shade: [0.8, '#fff']});
    $.ajax({
        url: url,
        success: function (data) {
            layer.close(layars);
            runAjaxResSuccess(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layer.close(layars);
            runAjaxResError(XMLHttpRequest, textStatus, errorThrown);
        }
    });
}

/**
 * 解析ajax请求成功时返回的数据
 * @param data
 */
function runAjaxResSuccess(data) {
    if (data.status === 1) {
        layer.msg(data.info, {
            icon: 1,
            time: 1000,
            shade: [0.8, '#fff']
        }, function (index) {
            //如果页面是在弹窗
            var indexbox = parent.layer.getFrameIndex(window.name);
            if (indexbox) {
                //关闭弹窗
                if (data.url) {
                    //goUrl(data.url, data.url.indexOf("#this") ? this : parent);
                    if (data.url.indexOf("#this") > 0) {
                        goUrl(data.url, window);
                    } else {
                        goUrl(data.url, parent);
                    }
                    return;
                } else {
                    parent.location.reload();
                }
                parent.layer.close(indexbox);
            }
            layer.close(index);
            if (data.url) {
                goUrl(data.url);
            }
        });
    } else if (data.status === 0) {
        layer.msg(data.info);
        // layer.alert(data.info, {
        //     title: warTitle,
        //     icon: 2
        // }, function (index) {
        //     //如果页面是在弹窗
        //     var indexbox = parent.layer.getFrameIndex(window.name);
        //     if (indexbox) {
        //         //关闭弹窗
        //         if (data.url) {
        //             goUrl(data.url, parent);
        //         }
        //         parent.layer.close(indexbox);
        //     }
        //     layer.close(index);
        //     if (data.url) {
        //         goUrl(data.url);
        //     }
        // });
    } else {
        layer.alert(errMsg, {
            icon: 0,
            title: errTitle
        });
    }
}


/**
 * 解析ajax请求失败时返回的数据
 * @param XMLHttpRequest
 * @param textStatus
 * @param errorThrown
 */
function runAjaxResError(XMLHttpRequest, textStatus, errorThrown) {
    var errorInfo = $(XMLHttpRequest.responseText).find('h1').text();
    layer.alert(errorInfo + '<br/>' + errMsg, {
        icon: 0,
        title: errTitle
    });
}

/**
 * 缩略图点击
 */
function coverClick() {
    $('.cover').on('click', function () {
        previewPictures($(this).attr('src'));
    });
}

/**
 * 预览图片
 * @param url
 */
function previewPictures(url) {
    layer.photos({
        photos: {
            "title": imgTitle, //相册标题
            "id": 1, //相册id
            "start": 0, //初始显示的图片序号，默认0
            "data": [   //相册包含的图片，数组格式
                {
                    "alt": imgTitle,
                    "pid": 1, //图片id
                    "src": url, //原图地址
                    "thumb": "" //缩略图地址
                }
            ]
        }
    });
}

/**
 * 预览列表
 * @param id
 */
function previewPicturesList(id) {
    layer.photos({
        photos: id
    });
}

/**
 * 切换显示与隐藏
 * @param jqobj
 */
function toggleShow(jqobj) {
    var list = jqobj.next();
    list.slideToggle('slow', function () {
        jqobj.html(list.css('display') == 'none' ? '点击显示' : '点击隐藏');
    });
}